package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock{

    private String name;
    private StringRedisTemplate stringRedisTemplate;

    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    private static final String key_prefix = "lock:";
    private static final String id_prefix = UUID.randomUUID().toString(true) + "-";
    private static final DefaultRedisScript<Long> unlock_script;
    // 静态代码块：在类加载时执行，用于初始化上面声明的 unlock_script 对象
    static {
        unlock_script = new DefaultRedisScript<>();
        unlock_script.setLocation(new ClassPathResource("unlock.lua"));
        unlock_script.setResultType(Long.class);
    }

    @Override
    public boolean tryLock(long timeoutSec) {
        //获取线程标识
        String threadId = id_prefix + Thread.currentThread().getId();
        //获取锁
        Boolean success = stringRedisTemplate.opsForValue()
                        .setIfAbsent(key_prefix+name, threadId, timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }

    public void unlock(){
        //调用lua脚本
        stringRedisTemplate.execute(
                unlock_script,
                Collections.singletonList(key_prefix + name),
                id_prefix + Thread.currentThread().getId());
    }
//    @Override
//    public void unlock() {
//        //获取线程标识
//        String threadId = id_prefix + Thread.currentThread().getId();
//        //获取锁中标识
//        String id = stringRedisTemplate.opsForValue().get(key_prefix + name);
//        //判断标识是否一致
//        if (threadId.equals(id)) {
//            //释放锁
//            stringRedisTemplate.delete(key_prefix+name);
//        }
//    }
}
